<template>
  <div>
    <el-button
      type="primary"
      @click="
        resetCompetition();
        dialogVisible = true;
      "
      >创建比赛</el-button
    >
    <el-table :data="competitions" style="width: 100%; margin-top: 20px">
      <el-table-column label="比赛ID" prop="id"></el-table-column>
      <el-table-column label="比赛名称" prop="name"></el-table-column>
      <el-table-column label="开始时间" prop="startTime"></el-table-column>
      <el-table-column label="结束时间" prop="endTime"></el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button @click="editCompetition(row)" type="text" size="small"
            >编辑</el-button
          >
          <el-button
            disabled
            @click="deleteCompetition(row.id)"
            type="text"
            size="small"
            style="color: red"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 创建/编辑比赛对话框 -->
    <el-dialog v-model="dialogVisible" title="创建/编辑比赛" width="50%">
      <el-form :model="competition">
        <el-form-item label="比赛名称" required>
          <el-input v-model="competition.name"></el-input>
        </el-form-item>
        <el-form-item label="开始时间" required>
          <el-date-picker
            v-model="competition.startTime"
            type="datetime"
            placeholder="选择开始时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" required>
          <el-date-picker
            v-model="competition.endTime"
            type="datetime"
            placeholder="选择结束时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="加入题目">
          <el-select
            v-model="selectedQuestion"
            placeholder="选择题目"
            clearable
          >
            <el-option
              v-for="question in questions"
              :key="question.id"
              :label="question.title"
              :value="question.id"
            />
          </el-select>
          <el-button
            type="primary"
            @click="addQuestionToCompetition"
            :disabled="!selectedQuestion"
            >加入题目</el-button
          >
          <el-table :data="competitionQuestions" style="margin-top: 20px">
            <el-table-column label="题目ID" prop="problemId"></el-table-column>
            <el-table-column
              label="题目标题"
              prop="problemTitle"
            ></el-table-column>
            <el-table-column label="操作">
              <template #default="{ row }">
                <el-button
                  @click="removeQuestionFromCompetition(row.problemId)"
                  type="text"
                  size="small"
                  style="color: red"
                  >移除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="saveCompetition">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";
import dayjs from "dayjs"; // 引入 dayjs 库
import utc from "dayjs/plugin/utc";
import timezone from "dayjs/plugin/timezone";

// 使用插件
dayjs.extend(utc);
dayjs.extend(timezone);
export default {
  data() {
    return {
      dialogVisible: false,
      competition: {
        id: null,
        name: "",
        startTime: "",
        endTime: "",
      },
      selectedQuestion: null,
      competitionQuestions: [], // 存储当前比赛已加入的题目
      questions: [], // 存储题目列表
      competitions: [], // 存储比赛列表
    };
  },
  created() {
    this.fetchCompetitions();
    this.fetchQuestions();
  },
  methods: {
    // 获取所有比赛
    async fetchCompetitions() {
      try {
        const res = await request.get("/contest/selectAll");
        this.competitions = res.data;
      } catch (error) {
        console.error("获取比赛数据失败");
      }
    },

    // 获取所有题目
    async fetchQuestions() {
      try {
        const res = await request.get("/problem/selectAllAdmin");
        // 过滤掉已在比赛中的题目
        const excludedProblemIds = this.competitionQuestions.map(
          (q) => q.problemId
        );
        this.questions = res.data.filter(
          (question) => !excludedProblemIds.includes(question.id)
        );
      } catch (error) {
        console.error("获取题目数据失败");
      }
    },

    // 编辑比赛
    async editCompetition(competition) {
      this.competition = { ...competition };
      try {
        // 通过比赛ID获取已加入的题目
        const res = await request.get(`/contest/${competition.id}/questions`);
        if (res.code === "200") {
          this.competitionQuestions = res.data || [];
        } else {
          this.$message.error("获取比赛题目失败");
        }
      } catch (error) {
        console.error("请求失败:", error);
        this.$message.error("请求失败");
      }

      // 在编辑时更新题目列表，排除已加入的题目
      this.fetchQuestions();

      this.dialogVisible = true;
    },

    // 取消操作
    cancel() {
      this.dialogVisible = false;
      this.resetCompetition();
    },

    // 重置比赛表单
    resetCompetition() {
      this.competition = {
        id: null,
        name: "",
        startTime: "",
        endTime: "",
      };
      this.competitionQuestions = [];
    },

    // 保存比赛（新增或更新）
    async saveCompetition() {
      // 转换开始时间和结束时间为 UTC 格式
      const startTime = dayjs(this.competition.startTime).tz("UTC").format();
      const endTime = dayjs(this.competition.endTime).tz("UTC").format();
      // 获取当前比赛数量
      const currentCompetitionCount = this.competitions.length;

      const competitionData = {
        name: this.competition.name,
        startTime: startTime, // 使用 UTC 格式时间
        endTime: endTime, // 使用 UTC 格式时间
        questions: this.competitionQuestions.map((q) => ({
          id: q.problemId, // 题目ID
          title: q.problemTitle, // 题目标题
        })),
      };

      // 如果是新比赛，传递比赛ID为当前比赛数量 + 1
      if (!this.competition.id) {
        competitionData.id = currentCompetitionCount + 1; // 创建新比赛时，ID = 当前比赛数量 + 1
      } else {
        competitionData.id = this.competition.id; // 编辑比赛时，传递已有ID
      }

      try {
        let res;
        if (this.competition.id) {
          // 编辑比赛
          res = await request.put(
            `/contest/update/${this.competition.id}`,
            competitionData
          );
        } else {
          // 创建新比赛
          res = await request.post("/contest/add", competitionData);
        }

        if (res.code === "200") {
          this.dialogVisible = false;
          this.fetchCompetitions();
          this.resetCompetition();
        } else {
          this.$message.error(res.msg);
        }
      } catch (error) {
        console.error("请求失败:", error);
      }
    },

    // 添加题目到比赛
    async addQuestionToCompetition() {
      const selected = this.questions.find(
        (q) => q.id === this.selectedQuestion
      );

      if (selected) {
        // 将选中的题目添加到比赛题目列表
        this.competitionQuestions.push({
          problemId: selected.id,
          problemTitle: selected.title,
        });

        // 清空选择框，避免重复选择同一个题目
        this.selectedQuestion = null;

        // 更新题目列表，避免重复题目
        this.fetchQuestions();
      }
    },

    // 移除题目
    removeQuestionFromCompetition(questionId) {
      const index = this.competitionQuestions.findIndex(
        (q) => q.problemId === questionId
      );
      if (index !== -1) {
        this.competitionQuestions.splice(index, 1);
        this.fetchQuestions(); // 重新加载题目列表
      }
    },
  },
};
</script>

<style scoped>
.dialog-footer {
  text-align: center;
  margin-top: 20px;
}
</style>
